package com.ruoyi.common.core.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字符串到Long列表的类型处理器
 * 用于处理GROUP_CONCAT结果到List<Long>的转换
 *
 * @author ruoyi
 */
public class StringToLongListTypeHandler extends BaseTypeHandler<List<Long>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null && !parameter.isEmpty()) {
            String value = parameter.stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            ps.setString(i, value);
        } else {
            ps.setString(i, null);
        }
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return convertStringToLongList(value);
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return convertStringToLongList(value);
    }

    @Override
    public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return convertStringToLongList(value);
    }

    private List<Long> convertStringToLongList(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        return Arrays.stream(value.split(","))
                .filter(StringUtils::hasText)
                .map(String::trim)
                .map(Long::valueOf)
                .collect(Collectors.toList());
    }
} 